<template>
  <div class="commission-composition-chart">
    <div v-if="loading" class="chart-loading">
      加载中...
    </div>
    <div v-else ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, defineProps, nextTick } from 'vue';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必需的组件
echarts.use([
  PieChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  CanvasRenderer
]);

// 定义组件属性
const props = defineProps({
  chartData: {
    type: Array,
    required: true
  }
});

// 图表DOM引用
const chartRef = ref(null);
// 图表实例
let chartInstance: echarts.ECharts | null = null;
// 加载状态
const loading = ref(true);

// 佣金类型对应的颜色
const typeColors = {
  orderCommission: '#FF4757',     // 订单佣金
  referralCommission: '#2196F3',  // 推荐佣金
  promotionCommission: '#4CAF50', // 促销佣金
  specialCommission: '#9C27B0'    // 特殊佣金
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  
  // 创建图表实例
  chartInstance = echarts.init(chartRef.value);
  
  // 设置加载状态
  loading.value = true;
  
  // 更新图表
  updateChart();
};

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || !props.chartData || props.chartData.length === 0) {
    loading.value = false;
    return;
  }
  
  // 准备数据
  const pieData = props.chartData.map(item => ({
    name: item.name,
    value: item.amount,
    percent: item.percent,
    itemStyle: {
      color: typeColors[item.type] || '#FF9800'
    }
  }));
  
  // 配置图表选项
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        const item = params.data;
        return `${item.name}<br />金额: ¥${item.value.toLocaleString('zh-CN', { minimumFractionDigits: 2 })}<br />占比: ${item.percent}%`;
      }
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      itemGap: 15,
      textStyle: {
        color: '#666'
      }
    },
    series: [
      {
        name: '佣金构成',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['30%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            formatter: '{b}: {d}%',
            fontSize: 14
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  };
  
  // 设置图表选项
  chartInstance.setOption(option);
  
  // 更新加载状态
  loading.value = false;
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 在组件挂载后初始化图表
onMounted(() => {
  nextTick(() => {
    initChart();
    window.addEventListener('resize', handleResize);
  });
});

// 监听数据变化
watch(() => props.chartData, () => {
  nextTick(() => {
    if (chartInstance) {
      updateChart();
    } else {
      initChart();
    }
  });
}, { deep: true });

// 组件卸载前清理
const onUnmounted = () => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener('resize', handleResize);
};
</script>

<style lang="scss" scoped>
.commission-composition-chart {
  width: 100%;
  height: 100%;
  position: relative;
}

.chart-container {
  width: 100%;
  height: 100%;
}

.chart-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  color: #999;
}

// 响应式处理
@media (max-width: 768px) {
  :deep(.echarts) {
    .legend {
      top: 'bottom' !important;
      right: 'auto' !important;
      orient: 'horizontal' !important;
    }
  }
}
</style> 